package com.example.springbootshiro.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.springbootshiro.dao.UserMapper;
import com.example.springbootshiro.entity.User;
import com.example.springbootshiro.security.PasswordHashed;
import com.example.springbootshiro.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Transactional
    @Override
    public int add(User user) {
        PasswordHashed ph = PasswordHashed.getInstance();
        user.setPassword(ph.encryptToHex(user.getPassword()));
        user.setSalt(ph.getCredentialsSalt());
        user.setPerms("user:user");
        user.setStatus("1");
        return userMapper.insert(user);
    }

    @Override
    public List<User> selectAll(String param) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (param != null && !"".equals(param)){
            queryWrapper.and(QueryWrapper -> QueryWrapper.like("name", param));
        }
        List<User> users = userMapper.selectList(queryWrapper);
        return users;
    }

    @Override
    public int update(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", user.getId());
        if (user.getPassword() != null  && !"".equals(user.getPassword())){
            PasswordHashed ph = PasswordHashed.getInstance();
            user.setPassword(ph.encryptToHex(user.getPassword()));
            user.setSalt(ph.getCredentialsSalt());
        }
        return userMapper.update(user,queryWrapper);
    }

    @Override
    public int delete(Long id) {
       // QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //queryWrapper.eq("id", user.getId());
        return userMapper.deleteById(id);
    }

    @Override
    public User selectOne(Long id) {
        return userMapper.selectById(id);
    }
}
